package
{
	import com.phantasy.caches.CacheLoader;
	import com.phantasy.globals.GameParameters;
	import com.phantasy.net.SocketCommand;
	import com.phantasy.net.connection.Connection;
	import com.phantasy.proto.m_auth_key_toc;
	import com.phantasy.proto.m_auth_key_tos;
	import com.phantasy.proto.m_role2_create_toc;
	import com.phantasy.proto.m_role2_create_tos;
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.system.Security;
	import flash.utils.Timer;
	import flash.utils.getTimer;

	[SWF(width = "1000", height = "600", backgroundColor = "#ffffff")]
	public class PreLoading extends Sprite
	{
		private var _gameLoading:GameLoading
		private var _createRoleLoader:CacheLoader;
		private var _mainLoader:CacheLoader;
		private var _createRole:MovieClip;
		private var _isAlreadLoad:Boolean;
		private var _timer:Timer;
		private var _timerValue:Number=0;
		public var authVo:m_auth_key_toc;
		public var beginLoadGameTime:int=0;
		
		public function PreLoading()
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.addEventListener(Event.RESIZE, this.resizeHandler);
			Security.allowDomain("*");
			Security.allowInsecureDomain("*");
			
			_createRoleLoader = new CacheLoader();
			_mainLoader = new CacheLoader();
			
			GameParameters.getInstance().initParameters(loaderInfo.parameters);
			
			if(GameParameters.getInstance().isDebug()){
				this._gameLoading = GameLoading.getInstance(this.loadTestLogin);
			}else{
				this._gameLoading = GameLoading.getInstance(this.initConnect);
			}
			
			this.addChildAt(_gameLoading,0);
			
		}
		
		private function loadTestLogin():void
		{
			
		}
		
		private function initConnect():void
		{
			this._timer = new Timer(100);
			this._timer.addEventListener(TimerEvent.TIMER, this.onTimer);
			this._gameLoading.itemLabel = "正在连接服务器";
			this._gameLoading.setTotalPercent(3, 100);
			
			Connection.getInstance().handlerSuccess = this.onConnectedServerSucc;
			Connection.getInstance().handlerSecurityError = this.onSecurityError;
			Connection.getInstance().handlerClose = this.onClose;
			Connection.getInstance().addSocketListener(SocketCommand.SYSTEM_ERROR,this.onSystemError);
			Connection.getInstance().addSocketListener(SocketCommand.AUTH_KEY,this.onAuthKey);
			Connection.getInstance().addSocketListener(SocketCommand.ROLE2_CREATE,this.creatRole);
			Connection.getInstance().startConnect();
		}
		
		private function onTimer(event:TimerEvent):void
		{
			this._timerValue++;
			this._timerValue = (this._timerValue % 100);
			_gameLoading.setItemPercent("正在连接服务器", this._timerValue, 100);
		}
		
		private function onTimerAuth(_arg1:TimerEvent):void
		{
			this._timerValue++;
			this._timerValue = (this._timerValue % 100);
			GameLoading.getInstance().setItemPercent("正在请求账号基本信息", this._timerValue, 100);
		}
		
		/**
		 *舞台缩放处理 
		 * @param event
		 * 
		 */		
		private function resizeHandler(event:Event):void
		{
				
		}
		
		/**
		 *连接服务器成功 
		 * 
		 */		
		private function onConnectedServerSucc():void
		{
			this._timer.stop();
			this._timerValue = 0;
			this._timer.removeEventListener(TimerEvent.TIMER, this.onTimer);
			GameLoading.getInstance().setTotalPercent(5, 100);
			GameLoading.getInstance().itemLabel = "正在请求账号信息";
			this._timer.addEventListener(TimerEvent.TIMER, this.onTimerAuth);
			this._timer.start();
			var date:Date;
			var authKey:m_auth_key_tos = new m_auth_key_tos();
			authKey.account_name = GameParameters.getInstance().account;
			authKey.key = GameParameters.getInstance().key;
			var tstamp:int = GameParameters.getInstance().tstamp;
			if(tstamp!=0){
				authKey.time = tstamp;
			}else{
				date = new Date();
				authKey.time = date.getTime()*0.001;
			}
			authKey.fcm = int(GameParameters.getInstance().fcm);
			Connection.getInstance().sendMessage(authKey);
			
		}
		
		private function onSystemError():void
		{
			
		}
		
		private function onAuthKey(message:m_auth_key_toc):void
		{
			if(message.succ){
				
				if (this._timer)
				{
					this._timer.stop();
					this._timer.removeEventListener(TimerEvent.TIMER, this.onTimerAuth);
					this._timer = null;
				}
				//如果是新账号的话
				if(message.need_create_role){
					GameParameters.getInstance().needToCreate=true;
					this.loadCreateRole();
				}else{
					this.authVo = message;
					this.loadGame();
				}
			}
		}
		
		/**
		 *加载创建人物 
		 * 
		 */		
		private function loadCreateRole():void
		{
			this._createRoleLoader.addEventListener(Event.COMPLETE, this.onCreateRoleLoadComplete);
			this._createRoleLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onCreateRoleLoadIOError);
			this._createRoleLoader.addEventListener(ProgressEvent.PROGRESS, this.onCreateRoleLoadProgress);
			this._createRoleLoader.load(new URLRequest("createRoleCQ2.swf"),true);
		}
		/**
		 *加载主程序 
		 * 
		 */		
		private function loadGame():void
		{
			if(_isAlreadLoad==false){
				_isAlreadLoad =true;
				if(GameParameters.getInstance().openCache=="1"){
					
				}else{
					loadGame2();
				}
			}
		}
		
		private function loadGame2():void
		{
			var mainURL:String;
			if(beginLoadGameTime==0)
			{
				this._gameLoading.loadWelcomeBG();
				this.beginLoadGameTime = getTimer();
				this._gameLoading.setTotalPercent(9, 100);
				
				this._mainLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onMainAppLoadComplete);
				this._mainLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onMainAppIOError);
				this._mainLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.onMainAppProgress);
				if (GameParameters.getInstance().isDebug())
				{
					mainURL = "Main.swf";
					this._mainLoader.load(new URLRequest(mainURL), true, new LoaderContext(false, ApplicationDomain.currentDomain));
				}
				else
				{
					mainURL = "Main.swf";
					this._mainLoader.load(new URLRequest(mainURL), true, new LoaderContext(false, ApplicationDomain.currentDomain));
				}
			}
		}
		
		private function onMainAppLoadComplete(event:Event):void
		{
			this._mainLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, this.onMainAppLoadComplete);
			this._mainLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onMainAppIOError);
			this._mainLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, this.onMainAppProgress);
			
			var mainDef:Class = (this._mainLoader.contentLoaderInfo.applicationDomain.getDefinition("Main") as Class);
			this.addEventListener("WAIT_AUTH_INFO", this.sendAuthInfo, true);
			this.addChildAt(mainDef["getInstance"](),0);
		}
		
		private function sendAuthInfo(event:Event):void
		{
			this.removeEventListener("WAIT_AUTH_INFO",sendAuthInfo,true);
			
			if(this.authVo!=null){
				Connection.getInstance().removeSocketListener(SocketCommand.SYSTEM_ERROR,onSystemError);
				var mainDef:Class = (this._mainLoader.contentLoaderInfo.applicationDomain.getDefinition("Main") as Class);
				mainDef["getInstance"]()["initAuthInfo"](this.authVo);
			}
		}
		
		private function onMainAppIOError(event:IOErrorEvent):void
		{
			refreshGame();
		}
		
		private function onMainAppProgress(event:ProgressEvent):void
		{
			var _local2:Number = ((this._mainLoader.bytesLoaded / 2) / this._mainLoader.bytesTotal);
			if (_local2 < 0.1)
			{
				_local2 = 0.1;
			}
			else
			{
				if (_local2 > 0.4)
				{
					_local2 = 0.4;
				}
			}
			GameLoading.getInstance().setTotalPercent(_local2, 1);
			GameLoading.getInstance().setItemPercent("加载游戏主文件", this._mainLoader.bytesLoaded, this._mainLoader.bytesTotal);
		}
		
		private function creatRole(message:m_role2_create_toc):void
		{
			var creatMainDef:Class;
			if (message.succ)
			{
				this.removeEventListener("CREATE_ROLE_REQUEST", this.onCreateRoleRequest, true);
				this._createRoleLoader.unLoad();
				this._createRoleLoader = null;
				this._createRole.stop();
				removeChild(this._createRole);
				this._createRole = null;
				this._gameLoading.visible = true;
			}
			else
			{
				creatMainDef = (this._createRoleLoader.contentLoaderInfo.applicationDomain.getDefinition("CreateMain") as Class);
				var createRole:MovieClip = creatMainDef["getInstance"]();
				createRole["completeHandler"](message.reason);
			}
		}
		
		private function onCreateRoleLoadComplete(event:Event):void
		{
			this._createRoleLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE,this.onCreateRoleLoadComplete);
			this._createRoleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onCreateRoleLoadIOError);
			this._createRoleLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, this.onCreateRoleLoadProgress);
			this._createRole = (this._createRoleLoader.contentLoaderInfo.content as MovieClip);
			this._gameLoading.visible=false;
			this.addEventListener("CREATE_ROLE_FLA_READY", this.onCreateRoleFlaReady, true);
			this.addChild(_createRole);
			this._createRole.x = (this.stage.stageWidth - 1002) * 0.5;
			loadGame();
		}
		
		private function onCreateRoleLoadIOError(event:IOErrorEvent):void
		{
			loadCreateRole();
		}
		
		private function onCreateRoleLoadProgress(event:ProgressEvent):void
		{
			this._gameLoading.setItemPercent("加载创建角色页面", event.bytesLoaded, event.bytesTotal);
		}
		/**
		 *创建角色准备好 
		 * @param event
		 * 
		 */		
		private function onCreateRoleFlaReady(event:Event):void
		{
			this.removeEventListener("CREATE_ROLE_FLA_READY", this.onCreateRoleFlaReady, true);
			var classDef:Class = (this._createRoleLoader.contentLoaderInfo.applicationDomain.getDefinition("CreateMain") as Class);
			this.addEventListener("CREATE_ROLE_REQUEST", this.onCreateRoleRequest, true);
			var createRole:MovieClip = classDef["getInstance"]();
			createRole["init"](loaderInfo.parameters);
			this.loadGame();
		}
		/**
		 *创建角色 
		 * @param event
		 * 
		 */		
		private function onCreateRoleRequest(event:DataEvent):void
		{
			var data:Array = event.data.split("|");
			var creatRole:m_role2_create_tos = new m_role2_create_tos();
			creatRole.sex = data[0];
			creatRole.category = data[1];
			creatRole.head = data[2];
			creatRole.role_name = data[3];
			Connection.getInstance().sendMessage(creatRole);
		}
		/**
		 *Socket安全沙箱报错 
		 * 
		 */		
		private function onSecurityError():void
		{
			refreshGame();
		}
		
		/**
		 *服务器关闭 
		 * 
		 */		
		private function onClose():void
		{
			refreshGame();
		}
		
		/**
		 *刷新游戏 
		 * 
		 */		
		private function refreshGame():void
		{
			
		}
	}
}